package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //检查参数    设备id  手机号+密码
        if (dto.getEquipmentId()==null&&(dto.getPhone()==null||dto.getPassword()==null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果包含手机号和密码
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户数据不存在");
            }
            String inPut = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!inPut.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //颁发token
            String token = AppJwtUtil.getToken(apUser.getId());
            Map map=new HashMap<>();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            //敏感信息置空     一般用vo封装
            map.put("user",apUser);

            return ResponseResult.okResult(map);
        }else {
            //使用设备id登录
            String token = AppJwtUtil.getToken(0);
            Map map=new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
